package com.bhs.sansonglogistics.ui.wallet;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.Constants;
import com.bhs.sansonglogistics.bean.AdvancePayment;
import com.bhs.sansonglogistics.bean.BankCardData;
import com.bhs.sansonglogistics.bean.BankCardList;
import com.bhs.sansonglogistics.bean.MenuBean;
import com.bhs.sansonglogistics.bean.event.OrderEvent;
import com.bhs.sansonglogistics.dialog.BottomSelectListDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.dialog.SelectBankCardDialog;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.login.PhoneNumberLoginActivity;
import com.bhs.sansonglogistics.ui.mine.PersonalInformationActivity;
import com.bhs.sansonglogistics.utils.EditTextUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.google.gson.Gson;

import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 提现
 */
public class WithdrawDepositActivity extends BaseActivity implements View.OnClickListener, NetCallBack {


    private TextView mTvBill;
    private EditText mEtMoney;
    private TextView mTvMayWithdrawDeposit;
    private TextView mTvMayFullWithdrawal;
    private LinearLayout mLlWithdrawDepositBankCard;
    private TextView mTvBankCard;
    private Button mBtnSubmit;
    private String balance;
    private IWXAPI msgApi;
    private ImageView mIvIcon;
    private SelectBankCardDialog selectBankCardDialog;
    private TextView mTvServiceCharge;
    private TextView mTvExpectedArrival;

    @Override
    public int initLayout() {
        return R.layout.activity_withdraw_deposit;
    }

    @Override
    public void initView() {
        //注册监听
        EventBus.getDefault().register(this);
        mTvBill = findViewById(R.id.tv_bill);
        mEtMoney = findViewById(R.id.et_money);
        mTvMayWithdrawDeposit = findViewById(R.id.tv_may_withdraw_deposit);
        mTvMayFullWithdrawal = findViewById(R.id.tv_may_full_withdrawal);
        mLlWithdrawDepositBankCard = findViewById(R.id.ll_withdraw_deposit_bank_card);
        mLlWithdrawDepositBankCard.setOnClickListener(this);
        mTvBankCard = findViewById(R.id.tv_bank_card);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mTvMayFullWithdrawal.setOnClickListener(this);
        mTvBill.setOnClickListener(this);
        networkRequest(netApi.get_bank_list(20), this);
        msgApi = WXAPIFactory.createWXAPI(mActivity, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.APP_ID);
        mIvIcon = findViewById(R.id.iv_icon);
        mTvServiceCharge = findViewById(R.id.tv_service_charge);
        mTvExpectedArrival = findViewById(R.id.tv_expected_arrival);
    }

    @Override
    public void initData() {
        balance = getIntent().getStringExtra("balance");
        mTvMayWithdrawDeposit.setText(String.format("可提现金额为%s元", balance));
        mEtMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                EditTextUtil.keepTwoDecimals(mEtMoney, 7);
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable editable) {
                verify();
                if (!TextUtils.isEmpty(mEtMoney.getText().toString())) {
                    double money = Double.parseDouble(mEtMoney.getText().toString());
                    BigDecimal bigDecimal = new BigDecimal(mEtMoney.getText().toString());
                    if (money >= 20) {
                        BigDecimal serviceCharge = bigDecimal.multiply(new BigDecimal("0.01"));
                        BigDecimal serviceCharge2 = bigDecimal.multiply(new BigDecimal("0.001"));
                        if (Double.parseDouble(serviceCharge2.toString()) < 1) {
                            serviceCharge2 = new BigDecimal("1");
                        }
                        String charge=String.format("%.2f",serviceCharge.add(serviceCharge2));
                        LogUtils.d(serviceCharge.add(serviceCharge2).toString());
                        mTvServiceCharge.setText(String.format("服务费：%s元", charge));
                        mTvExpectedArrival.setText(String.format("预计到账：%s元", bigDecimal.subtract(new BigDecimal(charge))));
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_may_full_withdrawal) {
            mEtMoney.setText(balance);
        } else if (view.getId() == R.id.tv_bill) {
            startActivity(new Intent(mActivity, WithdrawalRecordActivity.class));
        } else if (view.getId() == R.id.btn_submit) {
            loadingPopupShow();
            submit();
        } else if (view.getId() == R.id.ll_withdraw_deposit_bank_card) {
            bottomSelect();
        }
    }

    BottomSelectListDialog listDialog;

    private void bottomSelect() {
        selectBankCardDialog.show();
//        if (listDialog == null) {
//            List<MenuBean> list = new ArrayList<>();
//            list.add(new MenuBean("微信", R.mipmap.ic_we_chat));
//            //list.add(new MenuBean("支付宝", R.mipmap.ic_zhifubao));
//            list.add(new MenuBean("银行卡", R.mipmap.ic_bank_card));
//            list.add(new MenuBean("取消", 0));
//            listDialog = new BottomSelectListDialog(mActivity, list);
//            listDialog.setMyClickListener(new MyClickListener2() {
//                @Override
//                public void onClick(String id, String info) {
//                    if (id.equals("微信")) {
//                        weChat();
//                    }else if(id.equals("银行卡")){
//                        selectBankCardDialog.show();
//                    }
//                }
//            });
//        }
//        listDialog.show();
    }

    private void weChat() {
        if (TextUtils.isEmpty(SharedPreferencesUtils.getString(mActivity, "openid"))) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo"; // 只能填 snsapi_userinfo
            req.state = "sansong";
            msgApi.sendReq(req);
        } else {
            mTvBankCard.setText("微信");
            mTvBankCard.setTag("1");
            mIvIcon.setImageResource(R.mipmap.ic_we_chat);
        }
    }

    private void submit() {
        Map<String, String> map = new ArrayMap<>();
        map.put("number", mEtMoney.getText().toString());
        map.put("wallet_type", "money01");
        map.put("shoukuan_method", String.valueOf(mTvBankCard.getTag()));
        networkRequest(netApi.apply_withdraw(map), this, 888);
    }

    private void verify() {
        boolean verify = !TextUtils.isEmpty(mEtMoney.getText());
        if (verify && Double.parseDouble(mEtMoney.getText().toString()) < 20) {
            verify = false;
        }
        if (mTvBankCard.getTag() == null) {
            verify = false;
        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            BankCardData data = new Gson().fromJson(json, BankCardData.class);
            if (data.isStatus()) {
                selectBankCardDialog = new SelectBankCardDialog(mActivity, data.getData().getList());
                selectBankCardDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        mTvBankCard.setText(info);
                        mTvBankCard.setTag(id);
                        mIvIcon.setImageResource(R.mipmap.ic_bank_card);
                        verify();
                    }
                });
            } else {
                ToastUtil.show(data.getMsg());
            }
        } else if (requestCode == 888) {
            loadingPopupDismiss();
            AdvancePayment data = new Gson().fromJson(json, AdvancePayment.class);
            ToastUtil.show(data.getMsg());
            if (data.isStatus()) {
                finish();
                startActivity(new Intent(mActivity, WithdrawalProcessActivity.class).putExtra("withdraw_id", data.getData().getWithdraw_id()));
            }
        } else {


        }
    }

    @Subscribe
    public void onEvent(BaseResp event) {
        String Code = ((SendAuth.Resp) event).code;
        Map<String, String> map = new ArrayMap<>();
        map.put("appid", Constants.APP_ID);
        map.put("secret", Constants.secret);
        map.put("code", Code);
        map.put("grant_type", "authorization_code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        netApi.getAccess_token(url, map).enqueue(new Callback<ResponseBody>() {
            //请求成功回调
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    try {
                        mTvBankCard.setText("微信");
                        mTvBankCard.setTag("1");
                        mIvIcon.setImageResource(R.mipmap.ic_we_chat);
                        String body = response.body().string();
                        JSONObject jsonObject = new JSONObject(body);
                        String openid = jsonObject.getString("openid");
                        SharedPreferencesUtils.saveString(mActivity, "openid", openid);
                        networkRequest(netApi.update_user_info("openid", openid), WithdrawDepositActivity.this, 666);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.show("网络错误" + response.message() + response.code());
                }

            }

            //请求失败回调
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastUtil.show("网络错误" + t.toString());
            }
        });
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        networkRequest(netApi.get_bank_list(20), this);
    }
}